package com.bdqn.t320.ch06.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@RequestMapping("/file")
@Controller
public class FIleController {

    SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd/");


    @GetMapping(value = "/file")
    public String file() {
        return "file/file";
    }

    @PostMapping("/upload")
    public String upload(String uname, MultipartFile uploadFile, HttpServletRequest req) {
        //真实文件上传的路径,可以用nginx去发布
        String realPath = ("D:/img/");
        String format = sdf.format(new Date());
        //创建文件对象
        File folder = new File(realPath + format);
        //判断上传的目录是否存在
        if (!folder.isDirectory()) {
            //如果上传的目录不存在就创建
            folder.mkdirs();
        }
        //得到上传文件真实名称
        String oldName = uploadFile.getOriginalFilename();
        //获取文件后缀
        String suffixName = oldName.substring(oldName.lastIndexOf("."));
        //生成文件名称UUID
        UUID uuid = UUID.randomUUID();
        //uuid + 文件前缀组成新的文件名
        String newName = uuid.toString() + suffixName;
        try {
            //把内存中图片写入磁盘
            uploadFile.transferTo(new File(folder, newName));
        } catch (IOException e) {
            e.printStackTrace();
            return "上传失败! ";
        }
        return "redirect:/file/file";
    }
}
